package core.resources
{
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IOErrorEvent;
import flash.net.URLLoader;

import framework.dao.DataLoader;

import utils.URLUtil;

public class LoadTaskBase extends EventDispatcher
{
	//==========================================================================
    //  Constructor
    //==========================================================================
	public function LoadTaskBase()
	{
	}
    //==========================================================================
    //  Properties
    //==========================================================================
	public var params:*;
	
    protected var _isCompleted:Boolean;
    
    public function get isCompleted():Boolean
    {
    	return _isCompleted;
    }
    //==========================================================================
    //  Public methods
    //==========================================================================
    public function start():void
    {
    	
    }
    
    public function dispose():void
    {
    	
    }
	
	protected function startToLoad(url:String, onComplete:Function):void
	{
		var loader:URLLoader = new URLLoader();
		loader.addEventListener(IOErrorEvent.IO_ERROR, onError);
		loader.addEventListener(Event.COMPLETE, onComplete, false, 0);
		loader.addEventListener(Event.COMPLETE, onPreComplete, false, 5);
		loader.load(URLUtil.getRequest(url));
	}
	
	protected function startToLoadDataObject(url:String, ref:Class, onComplete:Function):void
	{
		var loader:DataLoader = new DataLoader();
		loader.url = url;
		loader.dataRef = ref;
		loader.addEventListener(IOErrorEvent.IO_ERROR, onError);	
		loader.addEventListener(Event.COMPLETE, onComplete, false, 0);	
		loader.addEventListener(Event.COMPLETE, onPreComplete, false, 5);	
		loader.start();
	}
	
	protected function onPreComplete(event:Event):void
	{
		event.target.removeEventListener(IOErrorEvent.IO_ERROR, onError);	
		event.target.removeEventListener(Event.COMPLETE, onPreComplete);
	}
	
	protected function onError(event:Event):void
	{
		event.target.removeEventListener(IOErrorEvent.IO_ERROR, onError);	
		event.target.removeEventListener(Event.COMPLETE, onPreComplete);
		
		throwError(event.toString());
	}
    
    protected function complete():void
    {
        _isCompleted = true;
        this.dispatchEvent(new Event(Event.COMPLETE));
    }
	
	protected function throwError(msg:String):void
	{
		var evt:ErrorEvent = new ErrorEvent(ErrorEvent.ERROR);
		evt.text = msg;
		this.dispatchEvent(evt);
	}
}
}